package uni.stuttgart.openstreetmap;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.*;

public class Panoramio {

	JsonData myJsonData;
	JsonDataList myJsonPhotoArray = new JsonDataList(5); // Beispiel hier nur 5 Bilder

	String testurl = "http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&minx=-180&miny=-90&maxx=180&maxy=90&size=medium";
	
	public Panoramio() {
		this.myJsonData = new JsonData();
	}
	
	public JsonDataList getPhotoArray (){
		return myJsonPhotoArray;
	}
	
	
	public void jsonParser (String url_input) throws IOException{
		try {
			url_input = testurl; // test here
			URL url = new URL(url_input);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			StringBuffer stb = new StringBuffer();
			String teststring = url.getFile();
			System.out.println(teststring);
			String line;
			while((line=br.readLine())!=null){
				stb.append(line);
			}
			//JSONObject jsonObject = new JSONObject(url_input);
			JSONObject jsonObject = new JSONObject(stb.toString());
			JSONArray jsonArray = jsonObject.getJSONArray("photos"); 
			for(int i=0;i<jsonArray.length();i++){
				myJsonData = new JsonData();
				JSONObject obj = (JSONObject)jsonArray.opt(i);			
				myJsonData.setJson_photo_id(obj.getInt("photo_id"));
				myJsonData.setJson_photo_title(obj.getString("photo_title"));
				myJsonData.setJson_photo_url(obj.getString("photo_url"));
				myJsonData.setJson_photo_file_url(obj.getString("photo_file_url"));
				myJsonData.setJson_upload_date(obj.getString("upload_date"));
				myJsonData.setJson_owner_id(obj.getInt("owner_id"));
				myJsonData.setJson_owner_name(obj.getString("owner_name"));				
				
				myJsonPhotoArray.addPhotoToArray(myJsonData);

				System.out.println("Titel: "+ obj.getString("photo_title"));
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
